﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Linq;

using Tools.Json;

using SY.Uap.Entity;
using SY.WebSite.Entity;
using SY.WebSite.BLL;

namespace SY.WebSite.Web.Handler
{
    public class RewardHandler : InternalWebHandler, IHttpHandler
    {
        public new void ProcessRequest(HttpContext context)
        {
            base.ProcessRequest(context);

            switch (Action)
            {
                case "query":
                    Query();
                    break;
                case "add":Add();
                    break;
                case "postResponse":
                    RewardResponse();
                    break;
                case "response":
                    GetResponseList();
                    break;
                case "finish":
                    Finish();
                    break;
                case "review":
                    Review();
                    break;
                default:
                    break;
            }

            context.Response.End();
        }

        public void Review()
        {
            int id = Tools.Web.Request.GetFormInt("id", 0);
            int rewardId = Tools.Web.Request.GetFormInt("rewardId", 0);
            int amount = Tools.Web.Request.GetFormInt("amount", 0);

            if (id <= 0 || rewardId <= 0)
                BreakResponse();

            Reward reward = BizReward.All().FirstOrDefault(l => l.Id == rewardId);
            if (reward == null || reward.UserId != CurrentUser.UserId || reward.Status != 0)
                BreakResponse();

            IEnumerable<RewardResponse> list = BizRewardResponse.GetListByRewardId(rewardId);
            RewardResponse response = list.FirstOrDefault(l => l.Id == id);
            if (response == null || response.Status != 0)
                BreakResponse();

            var tempAmount = list.Sum(l => l.Amount);
            if (tempAmount + amount > reward.Amount)
                BreakResponse("奖赏素币不能超过悬赏总素币");

            response.Status = 1;
            response.Amount = amount;

            int result = BizRewardResponse.Update(response);
            if (result > 0)
            {
                Response.Write(new JsonTransfer().Add("success", "success"));
                Response.End();
            }

            response.Status = 0;
            response.Amount = 0;
            BreakResponse();
        }

        public void Finish()
        {
            int id = Tools.Web.Request.GetFormInt("id", 0);

            if (id <= 0)
                BreakResponse();

            Reward reward = BizReward.All().FirstOrDefault(l => l.Id == id);
            if (reward == null || reward.Status == 1 || reward.UserId != CurrentUser.UserId)
                BreakResponse();

            if (BizReward.Finish(reward))
            {
                Response.Write(new JsonTransfer().Add("success", "success"));
                Response.End();
            }

            BreakResponse();
        }

        public void GetResponseList()
        {
            int id = RequestIntParam("id");
            int pageIndex = RequestIntParam("pageIndex");
            int pageSize = RequestIntParam("pageSize", 10);
            string never = RequestStringParam("never");

            bool my = RequestStringParam("my") == "true";

            if (id <= 0 || pageSize <= 0)
                BreakResponse();

            Reward reward = BizReward.All().FirstOrDefault(l => l.Id == id);
            if (reward == null)
                BreakResponse();

            JsonTransfer jt = new JsonTransfer();
            IEnumerable<RewardResponse> list = BizRewardResponse.GetListByRewardId(id);
            jt.Add("amount", list.Sum(l => l.Amount));
            jt.Add("count", list.Count());

            if (my)
                list = list.Where(l => l.UserId == CurrentUser.UserId);

            if (reward.Status == 0 && never == "true")
                list = list.Where(l => l.Status == 0);

            string order = RequestStringParam("order");
            if (order == "asc")
                list = list.Reverse();

            jt.Add("list", list.Skip(pageSize * pageIndex).Take(pageSize));
            Response.Write(jt);
        }

        public void RewardResponse()
        {
            string content = Tools.Web.Request.GetFormString("description");
            int id = Tools.Web.Request.GetFormInt("id", 0);

            if (id <= 0 || string.IsNullOrEmpty(content))
                BreakResponse();

            Reward reward = BizReward.All().FirstOrDefault(l => l.Id == id);
            if (reward == null || reward.EndTime < DateTime.Now)
                BreakResponse();

            RewardResponse response = new RewardResponse
            {
                RewardId = id,
                Content = Tools.StringUtil.HtmlEncode(content),
                UserId = CurrentUser.UserId,
                UserName = CurrentUser.UserName
            };

            int result = BizRewardResponse.Add(response);
            if (result > 0)
            {
                Response.Write(new JsonTransfer().Add("success", "success"));
                Response.End();
            }

            BreakResponse();
        }

        public void Add()
        {
            string title = Tools.Web.Request.GetFormString("title");
            string content = Tools.Web.Request.GetFormString("description");
            string end = Tools.Web.Request.GetFormString("end");
            string userList = Tools.Web.Request.GetFormString("userList");

            int amount = Tools.Web.Request.GetFormInt("amount", 0);
            int type = Tools.Web.Request.GetFormInt("type", 0);

            DateTime endTime = DateTime.Now;
            if (string.IsNullOrEmpty(title) || string.IsNullOrEmpty(content) || string.IsNullOrEmpty(end) ||
                type > 2 || type < 1 || amount == 0 || !DateTime.TryParse(end, out endTime))
                BreakResponse();

            Integration integration = BizIntegration.GetByKey(CurrentUser.UserId);
            if ((type == 1 && amount > integration.Available) || (type == 2 && amount > integration.Honor))
                BreakResponse();

            Reward reward = new Reward
                {
                    UserId = CurrentUser.UserId,
                    UserName = CurrentUser.UserName,
                    Title = Tools.StringUtil.HtmlEncode(title),
                    Description = Tools.StringUtil.HtmlEncode(content),
                    Amount = amount,
                    MayParticipateList = string.IsNullOrEmpty(userList) ? "" : ("," + userList.Trim(',') + ","),
                    EndTime = endTime,
                    Type = type,
                    Summary = Tools.StringUtil.GetSubString(Tools.StringUtil.RemoveHtml(content), 200, "...", Tools.StringUtil.StringFillOption.FillOneTimeWhenBeCut)
                };
            int result = BizReward.Add(reward);
            if (result > 0)
            {
                if (type == 1)
                {
                    integration.Available -= amount;
                }
                else
                {
                    integration.Honor -= amount;
                }
                integration.Freeze += amount;
                BizIntegration.Update(integration);

                Response.Write(new JsonTransfer().Add("id", result));
                Response.End();
            }

            BreakResponse();
        }

        public void Query()
        {
            int userId = RequestIntParam("userId");

            int pageIndex = RequestIntParam("pageIndex");
            int pageSize = RequestIntParam("pageSize", 10);

            string start = RequestStringParam("start");
            string end = RequestStringParam("end");
            string keyword = RequestStringParam("keyword");

            int type = RequestIntParam("type");//类型：100全部 0进行中 1结束

            IEnumerable<Reward> list = BizReward.All();
            list = list.Where(l => l.UserId == CurrentUser.UserId || string.IsNullOrEmpty(l.MayParticipateList) || l.MayParticipateList.Contains("," + CurrentUser.UserId + ","));

            if(!string.IsNullOrEmpty(keyword))
                list = list.Where(l=>l.Title.Contains(keyword) || l.Description.Contains(keyword));

            if (userId > 0)
            {
                User user = BizUser.GetByKey(userId);
                if (user == null)
                    BreakResponse();
                list = list.Where(l => l.UserId == userId);
            }

            if (type == 0 || type == 1)
                list = list.Where(l => l.Status == type);
            
            if(!string.IsNullOrEmpty(start))
            {
                DateTime starDate;
                if(DateTime.TryParse(start, out starDate))
                {
                    list = list.Where(l => l.CreateTime >= starDate);
                }
                else
                {
                    BreakResponse();
                }
            }

            if (!string.IsNullOrEmpty(end))
            {
                DateTime endDate;
                if (DateTime.TryParse(end, out endDate))
                {
                    list = list.Where(l => l.CreateTime <= endDate);
                }
                else
                {
                    BreakResponse();
                }
            }

            string deptName = RequestStringParam("deptName");
            if (!string.IsNullOrEmpty(deptName))
            {
                IList<Hashtable> userList = BizUser.LoadUserListWithFatProperty();
                IEnumerable<int> userIds = from c in userList where c["DeptName"].ToString().Contains(deptName.Trim()) select (int)c["UserId"];
                list = list.Where(l => userIds.Contains(l.UserId));
            }

            bool my = RequestStringParam("my") == "true";
            if (my)
                list = list.Where(l => l.UserId == CurrentUser.UserId);

            JsonTransfer jt = new JsonTransfer();
            jt.Add("count", list.Count());
            jt.Add("list", list.Skip(pageSize * pageIndex).Take(pageSize));
            Response.Write(jt);
        }
    }
}